#!/bin/sh

PATH=/sbin:/bin:/usr/bin:/usr/sbin

test -x /usr/sbin/ntpdate || exit 0

# load the defaults
if test -f /etc/default/ntpdate ; then
. /etc/default/ntpdate
fi

# try to get the NTP server from Enigma config
OVERRIDE=`grep "config.ntp.server" /etc/enigma2/settings | cut -d"=" -f 2`
if [ ! -z $OVERRIDE ]; then
	NTPSERVERS=$OVERRIDE
fi

# This is a heuristic:  The idea is that if a static interface is brought
# up, that is a major event, and we can put in some extra effort to fix
# the system time.  Feel free to change this, especially if you regularly
# bring up new network interfaces.
if [ "$METHOD" = static ]; then
	OPTS="-b"
fi

if [ "$METHOD" = loopback ]; then
	exit 0
fi

(

LOCKFILE=/var/lock/ntpdate

# Avoid running more than one at a time
if [ -x /usr/bin/lockfile-create ]; then
	lockfile-create $LOCKFILE
	lockfile-touch $LOCKFILE &
	LOCKTOUCHPID="$!"
fi

# wait until we have a network again
for i in {1..30}; do
	gw=`netstat -rn | grep UG | awk '{print $2}'`
	if [ ! -z "$gw" ]; then
		break
	fi
	sleep 1
done

if /usr/sbin/ntpdate -u -s $OPTS $NTPSERVERS 2>/dev/null; then
	if [ "$UPDATE_HWCLOCK" = "yes" ]; then
		hwclock --systohc || :
	fi
fi

if [ -x /usr/bin/lockfile-create ] ; then
	kill $LOCKTOUCHPID
	lockfile-remove $LOCKFILE
fi

) &
